package com.ny.zmb.glxt.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ny.zmb.glxt.entity.PmAm;
import com.ny.zmb.glxt.mapper.PmAmMapper;
import com.ny.zmb.glxt.service.IPmAmService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ny.zmb.openapi.entity.DataResult;
import com.ny.zmb.openapi.entity.PmUser;
import com.ny.zmb.openapi.mapper.PmUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 申请 高级别返利 或 分类代理 的表 服务实现类
 * </p>
 *
 * @author xie
 * @since 2024-10-22
 */
@Service
public class PmAmServiceImpl extends ServiceImpl<PmAmMapper, PmAm> implements IPmAmService {

    @Resource
    private PmAmMapper amMapper;
    @Resource
    private PmUserMapper userMapper;

    public IPage<PmAm> getPageList(IPage<PmAm> page, Wrapper<PmAm> queryWrapper) {
        return amMapper.selectPage2(page, queryWrapper.getEntity());
    }

    @Override
    public String getAllPid(PmUser pmUser) {
        StringBuffer pidArr = new StringBuffer();
        while (pmUser != null) {
            pmUser = getPmUserByPid(pmUser);
            if (pmUser != null) {
                pidArr.append(pmUser.getId());
            }
        }
        return pidArr.toString();
    }

    public PmUser getPmUserByPid(PmUser pmUser) {
        if (pmUser.getPid() == null || pmUser.getPid() == 0) {
            return null;
        }
        return userMapper.selectById(pmUser.getPid());
    }

    public PmUser getPmUserByPid(Long pid) {
        return userMapper.selectById(pid);
    }

    @Override
    @Transactional
    public DataResult<PmAm> sh(PmAm pmAm) {
        DataResult<PmAm> dataResult = new DataResult<>();

        PmAm upPmAm = new PmAm();
        PmUser upUser = new PmUser();

//        查询用户的信息
        PmAm xpmAm = amMapper.selectById(pmAm.getId());
        upPmAm.setId(pmAm.getId());
        if (pmAm.getStatus().equals("1")) {
            //审核通过
            dataResult.setCode("200");
            upPmAm.setStatus("1");
            //将用户状态改为对赌
            //如果申请的高级别返利 改变用户表的 level （等级）
            if (xpmAm.getSublx().equals("1")) {
            } else {
                //如果申请的是代理区域或者云仓 要将用户表的 agent_level（代理登记） agent_id （区域或云仓ID）
            }
            upUser.setId(xpmAm.getUserId());
            userMapper.updateById(upUser);
            amMapper.updateById(upPmAm);
        } else {
            dataResult.setCode("201");
            //审核不通过 改名申请的状态 写入拒绝理由
            upPmAm.setStatusRe(pmAm.getStatusRe());
            upPmAm.setStatus(pmAm.getStatus());
            amMapper.updateById(upPmAm);
        }

        return dataResult;
    }
}
